package com.example.demo.security;

import com.example.demo.entity.Users;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String num) throws UsernameNotFoundException {
        // 查找用户
        com.example.demo.entity.Users user = userRepository.findByUsername(num);

        if (user != null) {
            return User.withUsername(user.getUsername())
                    .password(user.getPassword())
                    .roles(user.getRoles().split(","))
                    .build();
        } else {
            // 记录更详细的错误信息
            System.err.println("User not found with username: " + num);
            throw new UsernameNotFoundException("User not found: " + num);
        }
    }

    public void registerUser(String num, String rawPassword, String... roles) {
        // 如果没有传递角色，默认设置为 "USER"
        if (roles.length == 0 || (roles.length == 1 && roles[0].isEmpty())) {
            roles = new String[]{"USER"};
        }

        // 编码密码并保存用户
        String encodedPassword = passwordEncoder.encode(rawPassword);
        Users newUser = new Users();
        newUser.setUsername(num);
        newUser.setPassword(encodedPassword);
        newUser.setRoles(String.join(",", roles));
        userRepository.save(newUser);
    }


    // 添加一个方法来验证用户密码
    public boolean validateUser(String num, String rawPassword) {
        com.example.demo.entity.Users user = userRepository.findByUsername(num);

        if (user == null) {
            return false;
        }
        // 验证密码
        return passwordEncoder.matches(rawPassword, user.getPassword());
    }
}
